<template>
  <div class="pages goodslistnew" id="app">
    <div class="pageLevel" v-if="!sub">
      <!-- 操作框 -->
      <div class="operationBox tableSearch">
        <el-button type="primary" size="mini" v-if="setRole('新增')" @click="routerPush()">新增</el-button>
        <el-button type="primary" size="mini" v-if="setRole('删除')" :disabled="statusDis" @click="deleteRows()">删除</el-button>
        <el-button type="primary" v-if="setRole('共享')" :disabled="dis||statusDis" size="mini" @click="handleFenpei()">共享</el-button>
        <a v-if="setRole('商品导入')" href="javascript:;" class="file">
          批量导入
          <input ref="uploading" @change="uploading($event)" type="file">
        </a>
        <el-button size="mini" v-if="setRole('商品导入')" type="primary" @click="donwloadMb()">下载模板</el-button>
     <!-- 菁姐产品 商米商品得不到单位，10.28上线这版批量导入，下载模版，先隐藏 -->
        <el-button type="primary" @click="onSetCommission" v-if="isShop==1&& setRole('设置商品提成')" size="mini">设置商品提成</el-button>

      </div>
      <!-- 搜索框 -->
      <div class="tableSearch">
        <el-form size="mini">
          <el-form-item label="" label-width="">
            <el-input v-model="selectdatas.keyword" placeholder="请输入商品条码.商品货号.名称" style="width:250px;"></el-input>
          </el-form-item>
          <!-- <el-form-item label="批号:" label-width="80px">
            <el-input v-model="selectdatas.pihao" placeholder="请输入批号"></el-input>
          </el-form-item> -->
          <el-form-item label="" label-width="15px">
            <el-button type="primary" icon="el-icon-search" @click="searchSelect" :disabled="dis" class="Button">查询</el-button>
          </el-form-item>
          <el-form-item label="" label-width="15px">
            <el-button type="primary" size="mini" @click="showmore=!showmore">高级查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 高级查询 -->
      <div class="tableSearch" v-show="showmore">
        <el-form label-width="100px" class="demo-ruleForm">
          <el-form-item label="商品分类：" label-width="100px" style="tableSearchs-f">
            <el-select size="mini" v-model="selectdatas.commodityClassification" placeholder="全部">
              <el-option v-for="(item, index) in saleStatusArray" :key="index" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否启用：" label-width="100px" style="tableSearchs-f">
            <el-select size="mini" v-model="selectdatas.isEnabled" placeholder="全部">
              <el-option label="全部" value=""></el-option>
              <el-option label="启用" value="0"></el-option>
              <el-option label="停用" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品货号：" label-width="100px" style="tableSearchs-f">
            <el-input size="mini" v-model="selectdatas.goodsCode" placeholder="请输入商品货号"></el-input>
          </el-form-item>
          <el-form-item label="商品条码：" label-width="100px">
            <el-input size="mini" v-model="selectdatas.barCode" placeholder="请输入商品条码"></el-input>
          </el-form-item>
          <el-form-item label="商品品牌：" label-width="100px">
            <!-- <el-input size="mini" v-model="selectdatas.goodsBrand" placeholder="请选择商品品牌"></el-input> -->
            <el-select filterable size="small" style="width:180px" v-model="selectdatas.goodsBrand" placeholder="请选择商品品牌" clearable>
              <el-option v-for="item in commodityBrandList" :key="item.index" :label="item.name" :value="item.id"> </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <!-- 表格 -->
      <div class="tableMain">
        <el-table :data="tableData" stripe style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" :selectable="puStatus"></el-table-column>
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
          <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
          <el-table-column prop="name" label="商品名称" align="center"></el-table-column>
          <el-table-column prop="primaryClassifyId" label="分类" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.primaryClassify}}</span>
              <span v-if="scope.row.secondaryName !=''">{{scope.row.secondaryName}}</span>
              <span v-if="scope.row.secondaryName !=''">{{scope.row.threeName}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="brand" label="品牌" align="center">
          </el-table-column>
          <el-table-column prop="parameterLong" label="规格型号" align="center">
            <template slot-scope="scope">
              <div v-for="(item,index) in scope.row.parameterLong" :key="index">
                <span v-if="item!=null">{{item.paramName}} :</span>
                <span v-if="item!=null"> {{item.paramValue}} </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="isCommission" label="是否提成" align="center" v-if="isShop=='1'">
            <template slot-scope="scope">
              <span v-if="scope.row.commissionValue == 0">否</span>
              <span v-else>是</span>
            </template>
          </el-table-column>
          <el-table-column prop="commissionValue" label="提成比例/金额" align="center" v-if="isShop=='1'">
            <template slot-scope="scope">
               <span v-if="scope.row.commissionValue != 0">
                 {{scope.row.commissionValue}}
                 <span v-if="scope.row.commissionWay == 0">%</span>
                 <span v-else>元</span>
               </span>
               <span v-if="scope.row.commissionValue == 0">
                --
               </span>
            </template>
          </el-table-column>
          <el-table-column prop="unitName" label="单位" align="center"></el-table-column>
          <el-table-column prop="status" align="center" label="是否启用" :formatter="statust"></el-table-column>
          <!-- <el-table-column prop="retailState" align="center" label="是否上架" :formatter="retailStatet"></el-table-column> -->
          <el-table-column prop="name" align="center" label="操作" width="180">
            <template slot-scope="scope">
              <el-button
                size="small"
                :disabled="dis"
                @click="routerPushLook('1',scope.row.id, scope.row.goodsCompanyId)"
                type="text"
                class="addDetail"
              >查看</el-button>
              <el-button
                size="small"
                v-if="setRole('修改')"
                @click="routerPushEdit('3',scope.row.id, scope.row.goodsCompanyId, scope.row.alloted)"
                type="text"
                class="addDetail"
              >修改</el-button>
              <el-button
                size="small"
                type="text"
                @click="routerPushEdit('3', scope.row.id, scope.row.goodsCompanyId, scope.row.isAllot, 1)"              v-if="setRole('商品知识')"
              >商品知识</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 页码 -->
        <div class="pageblock">
          <el-button size="small" type="primary" class="topage" @click="toPage">确定</el-button>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10,20,30,50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalItems"
          ></el-pagination>
        </div>
      </div>
      <el-dialog
        title="商户选择"
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <!-- 操作框 -->
        <div class="operationBox tableSearch">
          <el-button type="primary" :disabled="dis" @click="goBackM()" size="mini">返回</el-button>
          <el-button type="primary" :disabled="dis" @click="distribution" size="mini">分配</el-button>
        </div>
        <div class="tableSearch">
          <el-form label-width="100px" class="demo-ruleForm">
            <el-form-item label label-width="15px">
              <el-input
                class="input"
                v-model="selectdata.orgKey"
                size="small"
                placeholder="请输入商户名称"
              ></el-input>
            </el-form-item>
            <el-form-item label label-width="15px">
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="searchSelectOrg"
                class="Button"
              >查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table
          :data="tableData1"
          ref="multipleTable"
          max-height="550"
          @selection-change="changeFun"
        >
          <el-table-column type="selection" width="55" @selection-change="changeFun"></el-table-column>
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column property="shopCode" label="编号" align="center"></el-table-column>
          <el-table-column property="name" label="商户名称" align="center"></el-table-column>
          <el-table-column property="address" label="商户地址" align="center">
          </el-table-column>
        </el-table>
        <div class="pageblock">
          <el-button size="small" type="primary" class="topage1" @click="toPages">跳转</el-button>
          <el-pagination
            @size-change="handleSizeChanges"
            @current-change="handleCurrentChanges"
            :current-page="currentPages"
            :page-sizes="[10,20,30,50]"
            :page-size="pageSizes"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-dialog>
    </div>
    <div class="pageLevel" v-else>
      <router-view></router-view>
    </div>
    <!-- 设置商品提成 -->
    <el-dialog title="设置商品提成" :visible.sync="dialogFormVisible">
      <el-form :model="dialogForm" label-width="100px" size="mini">
        <el-form-item label="是否提成">
          <el-radio-group v-model="dialogForm.isCommission">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择提成方式" v-if="dialogForm.isCommission ==1">
          <el-select v-model="dialogForm.commissionType">
            <el-option label="比例提成" value="0"></el-option>
            <el-option label="固定提成" value="1"></el-option>
          </el-select>
          <el-input v-model="dialogForm.number" @keyup.native="dialogForm.number = util.replaceNumber(dialogForm.number)"></el-input>
          <span v-if="dialogForm.commissionType == 0">%</span>
          <span v-else>元</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="samll">取 消</el-button>
        <el-button type="primary" @click="onConfirmSet" size="samll">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from "vuex";
import ul from "@/util/state";
import util from "@/util";
import {
  findGoodsListPage,
  toLowerShop,
  leadGoods,
  updateGoodsStatus,
  getGoodsLabelList,
  getGoodsClassifyList,
  selectBaseShopPageList,
  updateGoodsDeduct // 批量设置提成
  //新增接口
} from "@/api";
export default {
  computed: mapState(["merchantId", "sub", "power", "soUrce", "isShop"]),
  data() {
    return {
      util: util,
      statust: ul.status, //列表中是否启用转化
      // retailStatet: retailState,
      saleStatusArray: [], //高级查询商品分类
      showmore: false, //高级查询的显示隐藏
      loading: false,
      tableData1: [],
      dialogVisible: false,
      multipleSelections: [],
      dis: false,
      statusDis: false, //商品为否时删除和分配到下级单位的样式
      // 搜索框
      selectdata: {
        select: "",
        status: "",
        keyword: "",
        orgKey: "",
        pihao: "",
        commodityClassification: "", //商品分类
        isEnabled: "", //是否启用
        barCode: "", //商品条码
        goodsCode: "", //商品货号
        goodsBrand: "" //商品品牌
      },
      selectdatas: {
        select: "",
        status: "",
        keyword: "",
        orgKey: "",
        pihao: "",
        commodityClassification: "", //商品分类
        isEnabled: "", //是否启用
        barCode: "", //商品条码
        goodsCode: "", //商品货号
        goodsBrand: "" //商品品牌
      },
      showmore: false,
      options: [],
      // 表格
      tableData: [],
      // 分页开始
      total: 0,
      pageSize: 20,
      totalItems: 0,
      currentPage: 1,
      // 分页开始
      pageSizes: 20,
      totalItemss: 0,
      currentPages: 1,
      commodityBrandList: [], //商品品牌数组
      dialogFormVisible: false,
      dialogForm: {
        isCommission: "1",
        commissionType: "1",
        number: ""
      },
      isAlloted: false
    };
  },
  mounted() {
    this.order(this.pageSize, this.currentPage);
    this.tableget_org(20, 1);
    this.repertory();
    this.commodityBrand();
  },
  watch: {
    sub: {
      handler: function(val, oldVal) {
        if (oldVal != null && val == false) {
          this.order(this.pageSize, this.currentPage);
          this.tableget_org(20, 1);
        }
      },
      deep: true
    }
  },
  methods: {
    //配置权限
    setRole(key) {
      return util.selectTitle(this.power, key);
    },
    // 商品品牌
    commodityBrand() {
      getGoodsLabelList({
        name: "",
        labelType: "0",
        shopId: this.merchantId
      }).then(res => {
        this.commodityBrandList = res.data.list;
      });
    },
    // 商品下拉
    repertory() {
      //商品品类下拉
      // let data = {
      //   shopId: this.merchantId
      // };
      // data
      getGoodsClassifyList().then(res => {
        this.saleStatusArray = res.data.list;
      });
    },
    handleFenpei() {
      if (this.multipleSelections.length > 0) {
        this.dialogVisible = true;
      } else {
        this.$message({
          showClose: true,
          message: "请先选择商品！",
          type: "error"
        });
      }
    },
    // 点击下载模板按钮
    donwloadMb() {
      let url = "";
      window.open(
        (url =
          "https://sd-picture-oss.oss-cn-beijing.aliyuncs.com/商品导入信息表.xlsx")
      );
    },
    uploading(event) {
      this.file = event.target.files[0]; //获取文件
      var windowURL = window.URL || window.webkitURL;
      //创建图片文件的url
      this.src = windowURL.createObjectURL(event.target.files[0]);
      //取消默认行为
      // event.preventDefault();
      let formdata = new FormData();
      formdata.append("file", this.file);
      formdata.append("shopId", this.merchantId);
      formdata.append("source", this.soUrce);

      // let formdata = {
      //   file: this.file,
      //   shopId: this.merchantId
      // };
      this.loading = true;
      leadGoods(formdata)
        .then(res => {
          if (res.code == "200") {
            this.$refs.uploading.value = null;
            this.loading = false;
            this.order(20, 1);
            this.$message({
              showClose: true,
              message: res.data,
              type: "success"
            });
          } else if (res.code == "10001") {
            let url = "";
            this.$message.error("导入失败,已在表格返回错误信息");
            // console.log(res.msg);
            window.open((url = res.msg));
          }
        })
        .catch(error => {})
        .finally((this.$refs.uploading.value = null));
    },

    //商户列表
    tableget_org(pageSize, pageNum) {
      let Data = {
        pageNum: pageNum,
        pageSize: pageSize,
        businessId: this.merchantId,
        status: 0,
        nameOrCode: this.selectdata.orgKey,
        type: "4"
      };
      selectBaseShopPageList(Data).then(res => {
        this.total = res.data.pageTotal;
        this.tableData1 = res.data.list;
        let aress = [];
        // this.tableData1.forEach((item, index) => {
        //   // console.log(item.area)
        //   if(item.area!=""){
        //      this.tableData1[index].aress = JSON.parse(item.area);
        //   }
        //   });
      });
    },
    searchSelectOrg() {
      this.tableget_org(this.pageSizes, 1);
    },
    // 多选
    handleSelectionChange(val) {
      this.multipleSelections = val;
      for (var i = 0; i < this.multipleSelections.length; i++) {
        if (this.multipleSelections[i].status == "1") {
          this.statusDis = true;
        }
        if (
          this.multipleSelections[i].status == "" ||
          this.multipleSelections[i].status == "0"
        ) {
          this.statusDis = false;
        } else {
        }
      }
    },
    //列表多选
    puStatus(row) {
      return row.status == 0;
    },
    // 点击删除按钮
    deleteRows() {
      var arr = [];
      for (var i = 0; i < this.multipleSelections.length; i++) {
        arr.push(this.multipleSelections[i].id);
      }
      let data = {
        id: arr.toString(),
        dr: "1"
      };
      if (this.multipleSelections.length > 0) {
        updateGoodsStatus(data).then(res => {
          this.$message({
            type: "success",
            message: res.msg
          });
          this.order(this.pageSize, this.currentPage);
        });
      } else {
        this.$message({
          type: "error",
          message: "请选择删除的商品"
        });
      }
    },
    changeFun(val) {
      this.isshop = true;
      this.multipleSelection = val;
    },
    //分配
    distribution() {
      var arr = [];
      var arrs = [];
      for (var i = 0; i < this.multipleSelection.length; i++) {
        arr.push(this.multipleSelection[i].id);
      }
      if (this.multipleSelections === undefined) {
        this.$message({
          type: "info",
          message: "请选择商品"
        });
        return false;
      }
      for (var i = 0; i < this.multipleSelections.length; i++) {
        arrs.push(this.multipleSelections[i].id);
      }
      let data = {
        goodsIds: arrs.toString(),
        shopIds: arr.toString()
      };
      toLowerShop(data).then(res => {
        this.$message({
          type: "success",
          message: "共享成功!"
        });
        this.dialogVisible = false;
      });
    },
    goBackM() {
      this.dialogVisible = false;
    },
    searchSelect() {
      this.selectdata = this.selectdatas;
      this.order(this.pageSize, 1);
    },
    //获取商品列表
    order(pageSize, pageNum) {
      let data = {
        name: this.selectdata.keyword,
        // key2: this.selectdata.pihao,
        pageNo: pageNum,
        pageSize: pageSize,
        shopId: this.merchantId,
        primaryClassifyId: this.selectdata.commodityClassification,
        status: this.selectdata.isEnabled,
        barCode: this.selectdata.barCode, //商品条码
        goodsCode: this.selectdata.goodsCode, //商品货号
        brandId: this.selectdata.goodsBrand //商品品牌
      };
      findGoodsListPage(data).then(res => {
        if (res.code == 200) {
          this.tableData = res.data.list;
          this.totalItems = res.data.total;
        }
      });
    },
    //商品---------------分页
    toPage(val) {
      this.order(this.pageSize, this.currentPage);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage=1;
      this.order(this.pageSize, this.currentPage);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.order(this.pageSize, this.currentPage);
    },
    //分配下级组织机构-----------分页
    toPages() {
      this.tableget_org(this.pageSizes, this.currentPages);
    },
    handleSizeChanges(val) {
      this.pageSizes = val;
      this.tableget_org(this.pageSizes, this.currentPages);
      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChanges(val) {
      this.currentPages = val;
      this.tableget_org(this.pageSizes, this.currentPages);
    },
    setRole(key) {
      return util.selectTitle(this.power, key);
    },
    // 新增路由
    routerPush() {
      util.routerTo(
        "/operate-management/goods-management/goods-goodslist/goods-goodsAddnew"
      );
    },
    // 查看路由
    routerPushLook(showTab, goosId = "", goodsCompanyId) {
      util.routerTo(
        "/operate-management/goods-management/goods-goodslist/goods-goodEditnew",
        {
          showTab: "1",
          goosId: goosId,
          goodsCompanyId: goodsCompanyId
        }
      );
    },
    // 编辑路由
    routerPushEdit(showTab, goosId = "", goodsCompanyId, alloted, isReading = "0") {
      util.routerTo(
        "/operate-management/goods-management/goods-goodslist/goods-goodEditnew",
        {
          showTab: "3",
          goosId: goosId,
          isReading: isReading,
          goodsCompanyId: goodsCompanyId,
          alloted: alloted
        }
      );
    },
    //  设置商品提成
    onSetCommission() {
      if (this.multipleSelections.length == 0) {
        this.$message.error("请勾选需要设置提成的商品");
      } else {
        this.dialogFormVisible = true;
      }
    },
    onConfirmSet() {
       if (this.dialogForm.isCommission == '1' && (!this.dialogForm.number || this.dialogForm.number == 0)) {
        this.$message.error('请输入提成值且大于0！')
        return
      }
      this.isAlloted = false
      let ids = [],
        data = {};
      for (let i = 0; i < this.multipleSelections.length; i++) {
        const element = this.multipleSelections[i];
        ids.push(element.id);
        if(element.alloted) {
          this.isAlloted = true
        }
      }
      if (this.isAlloted) {
        this.$message.error("已分配门店的商品,不能再设置提成")
        return false;
      }
      data = {
        goodsIds: ids.join(','),
        commissionWay: this.dialogForm.commissionType,
        commissionValue: this.dialogForm.number,
        shopId: this.merchantId
      };
      if(this.dialogForm.isCommission == 0) {
        data.commissionValue = 0;
      }

      updateGoodsDeduct(data).then(res => {
        if(res.code == 200) {
          this.dialogFormVisible = false;
          this.order(this.pageSize, this.currentPage);
        }
      });
    }
  }
};
</script>
<style scoped>
.el-dialog .el-input {
  width: 100px;
}
#app {
  text-align: left;
}
.showmore {
  display: block;
}
.file {
  position: relative;
  top: 10px;
  display: inline-block;
  background: #409eff;
  border: 1px solid #409eff;
  border-radius: 4px;
  padding: 4px 12px;
  margin: auto 10px;
  overflow: hidden;
  color: #fff;
  text-decoration: none;
  text-indent: 0;
  line-height: 18px;
  font-size: 10px;
}
.file input {
  position: absolute;
  right: 0;
  top: 0;
  opacity: 0;
}
.file:hover {
  background: #409eff;
  border-color: #409eff;
  color: #fff;
  text-decoration: none;
}
</style>
<style lang="">
.tableSearchs .el-select {
  width: 110px;
}

/*搜索的每个部分的样式*/

.tableSearchs .tableSearchs-f {
  float: left;
}
.tableSearchs .input {
  width: 290px;
}
</style>

